// pages/shop/category_new.js
var app = getApp();
var currentCateId = 0;

Page({
  data:{
    is_platform: false,
    act: 'create'
  },
  onLoad:function(options){
    // 页面初始化 options为页面跳转所带来的参数
    currentCateId = parseInt(options.id);
    
  },
  onReady: function(){
    if(currentCateId > 0 ){
      var that = this;
      app.func.req('product_cates/show', {
        id: currentCateId
      }, 'GET', function(res){
        if (res.code == 'success') {
          that.setData({
            category: res.result,
            act: 'update'
          })
          if (that.data.act == 'update') {
              wx.setNavigationBarTitle({
                  title: '编辑分类'
              })
          }
        }
      },{
        'token': wx.getStorageSync('token')
      });
    }
    this.getShopInfo(wx.getStorageSync('shop').id);
    
  },
  save:function(e){
    var params;
    if (this.data.act == 'create') {
      params = {
        name: e.detail.value.name,
        orderby: e.detail.value.orderby,
        is_platform: this.data.is_platform
      };
    } else {
      params = {
        id: this.data.category.id,
        name: e.detail.value.name,
        orderby: e.detail.value.orderby
      };
    }
    app.func.req('product_cates/' + this.data.act , params, 'POST', function(res){
      if (res.code == 'success') {
        wx.showToast({
          title: '添加成功！',
          icon: 'success',
          duration: 2000,
          mask: true,
          success: function(){
            wx.switchTab({
              url: './products'
            })
          }
        });
      } else if(res.msg == 'product_cates.name.exist') {
        wx.showToast({
          title: '分类已存在',
          image: '/images/fail.png',
          duration: 2000,
          mask: true
        });
      } else if (res.msg == 'product_cates.num.limit') {
        wx.showToast({
          title: '分类超过上限'+res.result +'个',
          image: '/images/fail.png',
          duration: 2000,
          mask: true
        });
      } else {
        wx.showToast({
          title: '添加失败',
          image: '/images/fail.png',
          duration: 2000,
          mask: true
        });
      }
    },{
      'token': wx.getStorageSync('token')
    });
  },
  platformSwitch: function() {
    this.setData({
      is_platform: !this.data.is_platform
    })
  },
  getShopInfo:function(shopId){
    var that = this;
    app.func.req('shops/info', {
      id: shopId
    }, 'GET', function (res) {
      if (res.code == "success") {
        if (res.result.lib_status == '1') {
          that.setData({
            is_open: true
          });
        } else{
          that.setData({
            is_open: false
          });
        }
      }
    }, {
        'token': wx.getStorageSync('token')
    });
  }
})
